if (typeof Promise === 'undefined') {
    Promise = require("./es6-promise.min.js").Promise;
}

const config = require("../config.js");
var userInfo = null;
var loginInfo = null;
function getSid() {
    return wx.getStorageSync('sid');
}
function clearSid() {
    console.log("清除sid...");
    wx.removeStorageSync('sid');
}
function wxLogin() {
    return new Promise((resolve, reject) => {
        console.log('wx.login...');
        wx.login({
            success: function (res) {
                console.log('wx.login complete');
                loginInfo = res;
                resolve(res);
            },
            fail: function () {
                console.log("wx.login fail");
                reject("wx.login fail");
            }
        })
    });
}

function wxGetUserInfo() {
    return new Promise((resolve, reject) => {
        console.log('wx.getUserInfo...');
        wx.getUserInfo({
            success: function (res) {
                console.log('【wx.getUserInfo】 complete');
                userInfo = res;
                wx.setStorageSync('user', res.userInfo);
                resolve(res);
            },
            fail: function () {
                console.log("【wx.getUserInfo】 fail");
                wx.showModal({
                    title: '提示',
                    showCancel: false,
                    content: '请您允许授权呢称和头像信息,并在接下来的提示中勾选用户信息并点击确定,谢谢！',
                    success: function (res) {
                        if (res.confirm) {
                            openSetting().then(r => {
                                clearSid();
                                userInfo = null;
                                loginInfo = null;
                                var ps = getCurrentPages();
                                var last = ps[ps.length - 1];
                                var url = "/" + last.__route__;
                                if (last.data.params) {
                                    var p = [];
                                    for (var k in last.data.params) {
                                        p.push(k + "=" + last.data.params[k]);
                                    }
                                    url += "?" + p.join("&");
                                }

                                console.log(url)
                                wx.redirectTo({
                                    url: url
                                })



                            }).catch(err => {
                                wx.switchTab({
                                    url: '/pages/home/home',
                                })
                            })
                        }
                    }
                })
            }
        })
    });
}


function openSetting() {
    return new Promise((resolve, reject) => {
        wx.openSetting({
            success(res) {
                if (res.authSetting['scope.userInfo'] === true) {
                    resolve();
                } else {
                    console.log(1212123)
                    reject();
                }
            },
            fail() {
                reject();
            }
        })
    })

}



class Net2 {
    constructor() {
        this.loginRetry = 5;
        this.requestRetry = 5;
    }
    login() {
        return new Promise((resolve, reject) => {
            if (getSid()) {
                console.log("login success");
                resolve();
                return;
            }
            wxLogin()
                .then(wxGetUserInfo)
                .then(() => {
                    if (!loginInfo || !userInfo) {
                        reject();
                    }
                    console.log('login start...');
                    wx.request({
                        url: config.login.url,
                        data: {},
                        method: 'GET',
                        header: { 'Code': loginInfo.code, 'Encrypted-Data': userInfo.encryptedData, 'IV': userInfo.iv },
                        success: (res) => {
                            if (res.data.status.code === 2000) {
                                console.log("login success");
                                wx.setStorageSync('sid', res.data.data.sid);
                                resolve(res);
                            } else {
                                reject(res);
                            }
                        },
                        fail: function () {
                            reject();
                        },
                    })
                });
        });
    }
    request(cfg) {
        var doRequest = function (arg) {
            wx.request({
                url: arg.url,
                data: arg.data,
                method: arg.method,
                header: arg.header,
                success: res => {
                    if (res.data.status.code === 2000) {
                        typeof arg.success === 'function' && arg.success(res.data);
                    } else {
                        this.requestRetry--;
                        //请求失败，重试
                        if (this.requestRetry > 0) {
                            console.warn('正在重试【', arg.url, '】');
                            if (res.data.status.code === 40001) {
                                clearSid();
                                this.request(cfg);
                            } else {
                                doRequest(arg);
                            }
                        } else {
                            typeof arg.fail === 'function' && arg.fail();
                        }
                    }
                },
                fail: function () {
                    typeof arg.fail === 'function' && arg.fail();
                },
            })
        }.bind(this);

        var opt = { requireLogin: true, data: {}, header: {} };
        for (var k in cfg) {
            opt[k] = cfg[k];
        }
        if (!opt.url) {
            console.warn("url参数错误");
            return;
        }
        console.log(opt)

        if (opt.requireLogin === true) {
            this.login().then(() => {
                opt.header.sid = getSid();
                doRequest(opt);
            }).catch(err => {
                console.log(err)
            });
        } else {
            doRequest(opt);
        }
    }
}



module.exports = {
    isLogin: getSid,
    get: cfg => {
        new Net2().request(cfg);
    },
    post: cfg => {
        cfg.method = 'POST';
        new Net2().request(cfg);
    },
}